<?php
declare (strict_types = 1);

namespace app\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\model\relation\BelongsToMany;
use think\model\relation\HasMany;

/**
 * @mixin Model
 */
class Enterprise extends Model
{

    public function member(): HasMany
    {
        return $this->hasMany(EnterpriseMember::class,'enterprise_id','id');
    }
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,
            'enterprise_member',
            'user_id',
            'enterprise_id');
    }
    /**
     * 获取用户的团队列表
     * @param int $user_id
     * @return array
     */
    public function getEnterpriseListByUserId(int $user_id): array
    {
        try {
            $rows = EnterpriseMember::where(['user_id' => $user_id])
                ->with(['enterprise', 'role'])
                ->select()->toArray();
            if (!$rows) {
                return [];
            }
            $data = [];
            foreach ($rows as $row) {
                $data[] = [
                    'id' => $row['enterprise']['id'],
                    'name' => $row['enterprise']['name'],
                    'role_name' => $row['role']['role_name'],
                    'avatar'=> $row['enterprise']['avatar'],
                    'role_id'=> $row['role']['id'],
                    'permissions'=> $row['role']['permissions'] ?: [],
                    'join_time'=> $row['join_time'],
                    'is_default'=> $row['is_default'],
                    'role_style'=> $row['role']['style']
                ];
            }
            return $data;
        } catch (DataNotFoundException|ModelNotFoundException|DbException) {
            return [];
        }
    }

    /**
     * 获取用户的默认团队信息
     * @param int $user_id
     * @return array
     */
    public function getDefaultEnterpriseByUserId(int $user_id): array
    {
        try {
            $row = EnterpriseMember::where(['user_id' => $user_id, 'is_default' => 1])
                ->with(['enterprise', 'role'])
                ->find()
                ->toArray();
            if (!$row) {
                return [];
            }
            return [
                'id' => $row['enterprise']['id'],
                'name' => $row['enterprise']['name'],
                'role_name' => $row['role']['role_name'],
                'avatar'=> $row['enterprise']['avatar'],
                'role_id'=> $row['role']['id'],
                'permissions'=> $row['role']['permissions'] ?: [],
                'join_time'=> $row['join_time'],
                'is_default'=> $row['is_default'],
                'role_style'=> $row['role']['style']
            ];
        }catch (DataNotFoundException|ModelNotFoundException|DbException){
            return [];
        }
    }
}
